package com.imgrate.migration.controller;

import com.imgrate.migration.entity.OperationLog;
import com.imgrate.migration.service.OperationLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/logs")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class OperationLogController {
    
    private final OperationLogService operationLogService;
    
    @GetMapping
    public ResponseEntity<List<OperationLog>> getAllLogs() {
        List<OperationLog> logs = operationLogService.getAllLogs();
        return ResponseEntity.ok(logs);
    }
    
    @GetMapping("/user/{username}")
    public ResponseEntity<List<OperationLog>> getLogsByUsername(@PathVariable String username) {
        List<OperationLog> logs = operationLogService.getLogsByUsername(username);
        return ResponseEntity.ok(logs);
    }
    
    @GetMapping("/operation/{operationType}")
    public ResponseEntity<List<OperationLog>> getLogsByOperationType(@PathVariable String operationType) {
        List<OperationLog> logs = operationLogService.getLogsByOperationType(operationType);
        return ResponseEntity.ok(logs);
    }
    
    @GetMapping("/time-range")
    public ResponseEntity<List<OperationLog>> getLogsByTimeRange(
            @RequestParam String start,
            @RequestParam String end) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(start, formatter);
            LocalDateTime endTime = LocalDateTime.parse(end, formatter);
            
            List<OperationLog> logs = operationLogService.getLogsByTimeRange(startTime, endTime);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("解析时间范围参数失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/user/{username}/time-range")
    public ResponseEntity<List<OperationLog>> getLogsByUsernameAndTimeRange(
            @PathVariable String username,
            @RequestParam String start,
            @RequestParam String end) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime startTime = LocalDateTime.parse(start, formatter);
            LocalDateTime endTime = LocalDateTime.parse(end, formatter);
            
            List<OperationLog> logs = operationLogService.getLogsByUsernameAndTimeRange(username, startTime, endTime);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("解析时间范围参数失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
}